package com.google.gwt.sample.dynatablerf.client.presenters;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.sample.dynatablerf.shared.GrifoRequestFactory;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
import com.google.gwt.view.client.SetSelectionModel;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.RequestContext;

public abstract class SingleSelectionDataPresenter<T extends EntityProxy, E extends RequestContext>
		extends AbstractSearchDataPresenter<T, E> {

	public interface SingleSelectionDataDisplay<T extends EntityProxy> extends
			SearchDataDisplay<T> {

		T getSelectedItem();

		SetSelectionModel<T> getSelectionModel();
	}

	public SingleSelectionDataPresenter(EventBus eventBus,
			GrifoRequestFactory requestFactory) {
		super(eventBus, requestFactory);
	}

	@Override
	protected void bind() {
		super.bind();

		getSingleSelectionDataDisplay().getSelectionChangedHandlers()
				.addSelectionChangeHandler(new Handler() {

					@Override
					public void onSelectionChange(SelectionChangeEvent event) {
						if (getSingleSelectionDataDisplay().getSelectedItem() != null) {
							onSingleSelection(getSingleSelectionDataDisplay()
									.getSelectedItem());
							getSingleSelectionDataDisplay().getSelectionModel()
									.clear();
						}

					}
				});
	}

	@Override
	protected SearchDataDisplay<T> getSearchDataDisplay() {
		return getSingleSelectionDataDisplay();
	}

	protected abstract SingleSelectionDataDisplay<T> getSingleSelectionDataDisplay();

	protected abstract void onSingleSelection(T selectedItem);

}
